package socialplaytime;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
 
@SuppressWarnings("serial")
public class PlaySetDataFrame extends JFrame {
	
	protected PlaySetDataPanel m_dp = new PlaySetDataPanel();
	protected PlaySet m_ps;
	protected JButton m_addButton = new JButton("Add");
	protected JButton m_updateButton = new JButton("Update");
	protected JButton m_deleteButton = new JButton("Delete");
	protected JButton m_saveButton = new JButton("Save");
	final JPanel panel = new JPanel();
	private String str1, str2, error;
	
	public PlaySetDataFrame(PlaySet playSet, PlayMenuGUI pmGUI){
		super("Data Management");
		this.m_ps = playSet;
		buildLayout();
		pack();
	}
	
	private void clearTextfield(){
		m_dp.nameField.setText("");
		m_dp.choiceField.setText("");
	}
	
	private void getTextfield() {
		str1 = m_dp.nameField.getText();
		str2 = m_dp.choiceField.getText();
	}
	
	protected void buildLayout(){
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container pane = getContentPane();
		pane.setLayout(new BorderLayout());
		
		pane.add(m_dp, BorderLayout.CENTER);

		m_addButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				getTextfield();
				error = m_ps.add(str1, str2);
				clearTextfield();
				if(!error.equals("success"))
					JOptionPane.showMessageDialog(panel, error, "Error", JOptionPane.ERROR_MESSAGE);
			}
		});
		
		m_updateButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				getTextfield();
				error = m_ps.update(str1, str2);	
				clearTextfield();
				if(!error.equals("success"))
					JOptionPane.showMessageDialog(panel, error, "Error", JOptionPane.ERROR_MESSAGE);
			}
		});
		
		m_deleteButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				getTextfield();
				error = m_ps.delete(str1, str2);	
				clearTextfield();
				if(!error.equals("success"))
					JOptionPane.showMessageDialog(panel, error, "Error", JOptionPane.ERROR_MESSAGE);
			}
		});
		
		m_saveButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				clearTextfield();
				m_ps.resetPlay();	
				dispose();	
			}
		});
		JPanel panel = new JPanel();
		panel.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 15));
		panel.add(m_addButton);
		panel.add(m_updateButton);
		panel.add(m_deleteButton);
		panel.add(m_saveButton);
		pane.add(panel, BorderLayout.SOUTH);
	}
}
